// 认证状态管理
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '@/services/api.js'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('auth_token') || '')
  const user = ref(JSON.parse(localStorage.getItem('auth_user') || 'null'))
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userInfo = computed(() => user.value)

  // 登录方法
  const login = async (credentials) => {
    try {
      isLoading.value = true
      
      const response = await authAPI.login(credentials)
      
      if (response.code === 200) {
        const { token: authToken, user: userInfo, expires_at } = response.data
        
        // 保存token和用户信息
        token.value = authToken
        user.value = userInfo
        
        // 持久化存储
        localStorage.setItem('auth_token', authToken)
        localStorage.setItem('auth_user', JSON.stringify(userInfo))
        localStorage.setItem('auth_expires_at', expires_at)
        
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      let message = '登录失败'
      
      if (error.response?.data?.message) {
        message = error.response.data.message
      } else if (error.response?.status === 401) {
        message = '用户名或密码错误'
      } else if (error.response?.status >= 500) {
        message = '服务器错误，请稍后重试'
      } else if (error.code === 'ECONNREFUSED') {
        message = '无法连接到服务器'
      }
      
      return { success: false, message }
    } finally {
      isLoading.value = false
    }
  }

  // 注册方法
  const register = async (userData) => {
    try {
      isLoading.value = true
      
      const response = await authAPI.register(userData)
      
      if (response.code === 201) {
        const { token: authToken, user: userInfo, expires_at } = response.data
        
        // 保存token和用户信息
        token.value = authToken
        user.value = userInfo
        
        // 持久化存储
        localStorage.setItem('auth_token', authToken)
        localStorage.setItem('auth_user', JSON.stringify(userInfo))
        localStorage.setItem('auth_expires_at', expires_at)
        
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message || '注册失败' }
      }
    } catch (error) {
      console.error('注册错误:', error)
      let message = '注册失败'
      
      if (error.response?.data?.message) {
        message = error.response.data.message
      } else if (error.response?.status === 409) {
        message = '用户名或邮箱已存在'
      } else if (error.response?.status >= 500) {
        message = '服务器错误，请稍后重试'
      } else if (error.code === 'ECONNREFUSED') {
        message = '无法连接到服务器'
      }
      
      return { success: false, message }
    } finally {
      isLoading.value = false
    }
  }

  // 登出方法
  const logout = () => {
    // 清除状态
    token.value = ''
    user.value = null
    
    // 清除本地存储
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
    localStorage.removeItem('auth_expires_at')
    

  }

  // 检查token是否过期
  const checkTokenExpiry = () => {
    const expiresAt = localStorage.getItem('auth_expires_at')
    if (expiresAt) {
      const now = new Date()
      const expiry = new Date(expiresAt)
      
      if (now >= expiry) {
        logout()
        return false
      }
    }
    return true
  }

  // 初始化认证状态
  const initAuth = () => {
    if (token.value) {
      // 检查token是否过期
      checkTokenExpiry()
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    try {
      const response = await authAPI.profile()
      if (response.code === 200) {
        user.value = response.data
        localStorage.setItem('auth_user', JSON.stringify(response.data))
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error)
    }
  }

  // 更新个人资料
  const updateProfile = async (userData) => {
    try {
      isLoading.value = true
      
      const response = await authAPI.updateProfile(userData)
      
      if (response.code === 200) {
        user.value = response.data
        localStorage.setItem('auth_user', JSON.stringify(response.data))
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.message || '更新失败' }
      }
    } catch (error) {
      console.error('更新个人资料错误:', error)
      let message = '更新失败'
      
      if (error.response?.data?.message) {
        message = error.response.data.message
      } else if (error.response?.status === 409) {
        message = '邮箱已被使用'
      } else if (error.response?.status >= 500) {
        message = '服务器错误，请稍后重试'
      }
      
      return { success: false, message }
    } finally {
      isLoading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    try {
      isLoading.value = true
      
      const response = await authAPI.changePassword(passwordData)
      
      if (response.code === 200) {
        return { success: true, message: '密码修改成功' }
      } else {
        return { success: false, message: response.message || '密码修改失败' }
      }
    } catch (error) {
      console.error('修改密码错误:', error)
      let message = '密码修改失败'
      
      if (error.response?.data?.message) {
        message = error.response.data.message
      } else if (error.response?.status === 400) {
        message = '当前密码不正确'
      } else if (error.response?.status >= 500) {
        message = '服务器错误，请稍后重试'
      }
      
      return { success: false, message }
    } finally {
      isLoading.value = false
    }
  }

  return {
    // 状态
    token,
    user,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    userInfo,
    
    // 方法
    login,
    register,
    logout,
    checkTokenExpiry,
    initAuth,
    refreshUserInfo,
    updateProfile,
    changePassword
  }
})
